
import re,random
from flask import current_app
from flask import make_response
from flask import request,jsonify

from info import redis_store,constants

from info.utils.response_code import RET

from . import passport_blue

from info.utils.captcha.captcha import captcha
# 导入运通信
from info.libs.yuntongxun import sms

@passport_blue.route('/image_code')
def generate_image_code():

    # 获取参数
    image_code_id = request.args.get('image_code_id')
    if not image_code_id:
        return jsonify(errno = RET.PARAMERR,errmsg='参数缺失')
    # 调用captcha工具生成图片验证码
    name,text,image = captcha.generate_captcha()
    # 在redis中保存图片验证码的内容
    try:
        redis_store.set('ImageCode_'+image_code_id,constants.IMAGE_CODE_REDIS_EXPIRES.text)
    except Exception as e:
        current_app.logger.erroe(e)
        return jsonify(errno=RET.DBERR,errmsg='保存图片验证码失败')
    else:
        # 设置响应对象返回图片验证码
        response = make_response(image)
        # 设置响应类型
        response.headers['Content_Type']='image/jpg'
        # 返回响应
        return response

@passport_blue.route('/sms_code',methods=['post'])

def send_sms_code():
    # 获取参数
    mobile = request.json.get('mobile')
    image_code = request.json.get('image_code')
    image_code_id = request.json.get('image_code_id')
    # 判断完整性
    if not all(mobile,image_code,image_code_id):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    # 检查手机号格式，使用正则
    if not re.mach(r'1[3456789]\d{9}$',mobile):
        return jsonify(errno=RET.PARAMERR,errmsg='手机号格式错误')
    try:
        real_image_code = redis_store.get('ImageCode_'+image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='获取图片验证码异常')
    # 判断获取结果是否有数据
    if not real_image_code:
        return jsonify(errno=RET.NODATA,errmsg='图片验证码已过期')
    try:
        redis_store.delete('ImageCode'+image_code_id)
    except Exception as e:
        current_app.logger.error(e)
    # 比较图片验证码是否正确
    if real_image_code.lower()!= image_code.lower():
        return jsonify(errno=RET.DATAERR,errmsg='图片验证码错误')
    # 构造图片验证码
    sms_code = '%06d'%random.randint(0,999999)
    # 把短信随机数保存到redis数据库中
    try:
        redis_store.setex('SMSCode_'+mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='保存短信图片验证码异常')
    # 调用运通讯，发送短信
    try:
        ccp = sms.CCP()
        result = ccp.send_template_sms(mobile,[sms_code,constants.SMS_CODE_REDIS_EXPIRES/60,1])
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg='发送短信异常')
    if result == 0:
        return jsonify(errno=RET.OK,errmsg='发送成功')
    else:
        return jsonify(errno=RET.THIRDERR,errmsg='发送失败')












    pass